﻿using System;
using System.Net;
using System.Text;
using System.Collections.Generic;

namespace CRM.Tools.ODataQueryDesigner.Helpers
{
    public static class ODataBuilder
    {
        /// <summary>
        /// Buils the OData query string
        /// </summary>
        /// <param name="Select"></param>
        /// <param name="OrderBy"></param>
        /// <param name="Filter"></param>
        /// <param name="Expand"></param>
        /// <returns></returns>
        public static string BuildQuery(List<String> Select, List<String> OrderBy, List<String> Filter, List<String> Expand)
        {
            StringBuilder query = new StringBuilder();

            if (Select.Count > 0)
            {
                query.Append("$select=");

                for (int counter = 0; counter < Select.Count; counter++)
                {
                    if (counter == Select.Count - 1)
                        query.Append(Select[counter]);
                    else
                    {
                        query.Append(Select[counter]);
                        query.Append(",");
                    }
                }
            }

            if (OrderBy.Count > 0)
            {
                if(query.Length>0)
                    query.Append("&");

                query.Append("$orderby=");

                for (int counter = 0; counter < OrderBy.Count; counter++)
                {
                    if (counter == OrderBy.Count - 1)
                        query.Append(OrderBy[counter]);
                    else
                    {
                        query.Append(OrderBy[counter]);
                        query.Append(",");
                    }
                }
            }

            if (Expand.Count > 0)
            {
                if (query.Length > 0)
                    query.Append("&");

                query.Append("$expand=");

                for (int counter = 0; counter < Expand.Count; counter++)
                {
                    if (counter == Expand.Count - 1)
                        query.Append(Expand[counter]);
                    else
                    {
                        query.Append(Expand[counter]);
                        query.Append(",");
                    }
                }
            }

            if (Filter.Count > 0)
            {
                if (query.Length > 0)
                    query.Append("&");

                query.Append("$filter=");

                for (int counter = 0; counter < Filter.Count; counter++)
                {
                    query.Append(Filter[counter]);
                }
            }   


            return query.ToString();
        }
    }
}
